using System.Collections;
using AutoChess;
using Table.Blo;
using UnityEngine;

namespace AutoChess
{
    /// <summary>
    /// 模型拓展操作组件
    /// </summary>
    class DragModelContainer
    {
        private CellModelLoadHelper cellLoadHelper;
        private GameObject modelParent;
        public GameObject ModelParent
        {
            get
            {
                if (modelParent == null)
                {
                    modelParent = new GameObject("ModelRoot");
                    modelParent.transform.SetParent(AutoChessFieldViewCtr.Ins.HeroUnitRoot);
                    modelParent.transform.Normalize();
                }
                return modelParent;
            }
        }
        public DragModelContainer(ACHero heroUnint)
        {
            cellLoadHelper = new CellModelLoadHelper(ModelParent.transform,AutoChessFieldViewCtr.Ins.LoadEventManager,"town",null,false);
            
            LoadModel(heroUnint);
            cellLoadHelper.ResetModelLayer(LayerName.SceneActor);
            
            var grid = heroUnint.MapGrid;
            SetDragModelOffset(heroUnint.HeroID, grid.GridType);

            ModelParent.transform.position = grid.ActorTrans.Position;
            cellLoadHelper.SetTransparency(0.3f);
            
            //TODO 功能特性封装 ， 需要一个携程管理器
            AutoChessFieldViewCtr.Ins.StartCoroutine("CheckModelLoadCompolate");
        }

        public void UpdateRotation(float angle)
        {
            cellLoadHelper.SetModelAngle(new Vector3(0, angle, 0));
        }
        public void UpdatePosition(Vector3 pos)
        {
            ModelParent.transform.position = pos;
        }
        
        IEnumerator CheckModelLoadCompolate()
        {
            while (true)
            {
                cellLoadHelper.Update();
                yield return null;
            }
        }
        
        private void SetDragModelOffset(int heroId, GridType gridType)
        {
            Vector3 scale = Vector3.one;
            var dictModel = Table.Blo.TableSailorModelBlo.GetTableSailorModelByHeroIdAndAppearence(heroId, 0);
            if (dictModel != null)
            {
                scale *= 0.85f * (float)dictModel.ModelScale * AutoChessBlo.GetFieldScale(heroId);
            }
            cellLoadHelper.SetModelOffset(Vector3.zero, scale, new Vector3(0, 90, 0));
        }
        
        private void LoadModel(ACHero heroUnit)
        {
            var guid = heroUnit.OwnerPlayerUID;
            int fashtionId = 0;
            if (guid != 0)
            {
                fashtionId = AutoChessManager.Ins.cacheData.GetPlayerHeroFathionId(guid,heroUnit.HeroID);
            }
            cellLoadHelper.SetData(heroUnit.HeroID, fashtionId);
            cellLoadHelper.LoadModel();
        }

        public void Release()
        {
            AutoChessFieldViewCtr.Ins.StopCoroutine("CheckModelLoadCompolate");
            cellLoadHelper.UnloadModel();
        }
    }
}